<template>
  <div class="card-carousel" @mouseenter="isHover = true" @mouseleave="isHover = false">
    <div class="card-carousel__wrapper" :class="[modelValue?.width ? `container-content-${modelValue?.width}` : 'container-content']">
      <client-only v-if="showCarousel && isShow">
        <swiper
          ref="swiperRef"
          :modules="modules"
          :centered-slides="false"
          :speed="600"
          :slides-per-view="1"
          :slides-per-group="1"
          :space-between="16"
          :short-swipes="true"
          :long-swipes-ratio="0.3"
          :loop="true"
          :auto-height="true"
          :breakpoints="breakpoints"
          class="swiper card-carousel__swiper"
          @slideChange="onSwiperSlideChange"
          @swiper="onSwiperReady"
        >
          <swiper-slide
            v-for="(item, index) in modelValue?.data"
            :key="item.id"
            class="swiper-slide"
            @click="handleSlideClick(index)"
          >
            <div class="slide-content">
              <div class="card-profile">
                <div class="profile__head">
                  <div class="profile__img img-fit --show-profile">
                    <img :src="item.imgSrc" :alt="item.alt" />
                    <div class="profile__img__mask">
                      <div class="profile__img__mask__btn">
                        简介
                      </div>
                    </div>
                  </div>
                </div>
                <div class="profile__body text-center --show-profile">
                  <div class="profile__title tx-subtitle mt-3 mt-md-4">
                    {{ item.title }}
                  </div>
                  <h6 class="profile__name tx-h6 mt-md-1">
                    {{ item.name }}
                  </h6>
                </div>
              </div>
            </div>
          </swiper-slide>
        </swiper>
        <div class="mt-10 mt-md-12">
          <SlidesPagination
            :currentIndex="currentIndex"
            :count="pageCount"
            @updatePage="updatePage"
            @slidePrev="slidePrev"
            @slideNext="slideNext"
            dark
            :isLoop="true"
          ></SlidesPagination>
        </div>
      </client-only>
      <div v-else>
        <div class="row row-cols-1 row-cols-md-3 row-cols-lg-4 justify-content-center">
          <div
            class="card-content"
            v-for="item in modelValue?.data" :key="item.id" @click="handleClick(item)"
          >
            <div class="card-profile">
              <div class="profile__head">
                <div class="profile__img img-fit --show-profile">
                  <img :src="item.imgSrc" :alt="item.alt" />
                  <div class="profile__img__mask">
                    <div class="profile__img__mask__btn">
                      简介
                    </div>
                  </div>
                </div>
              </div>
              <div class="profile__body text-center --show-profile">
                <div class="profile__title tx-subtitle mt-3 mt-md-4">
                  {{ item.title }}
                </div>
                <h6 class="profile__name tx-h6 mt-md-1">
                  {{ item.name }}
                </h6>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <Operate v-if="!isPreview" v-model:show="isHover" @handle-edit="showSetting = true" @handle-delete="handleDelete" @handle-copy="handleCopy" @handle-paste="handlePaste"></Operate>
  </div>

  <Setting v-if="!isPreview" v-model:show="showSetting" :data="modelValue"></Setting>
  <ProfileModel v-model:show="showProfile" :data="profileData"></ProfileModel>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { Swiper, SwiperSlide } from "swiper/vue";
import { Navigation, Pagination, Autoplay } from 'swiper/modules';
// 导入 Swiper 样式
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
import { randomString } from '@/utils/common'
import Setting from './setting.vue'
import Operate from '@/common/Operate/index.vue'
import ProfileModel from '@/common/Profile/modal.vue'
import SlidesPagination from "@/common/SlidesPagination/index.vue";

// 定义组件名称
defineOptions({
  name: 'CardCarousel'
})

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => {}
  },

  // 是否预览
  isPreview: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['update:modelValue', 'handleDelete', 'handleCopy', 'handlePaste'])

const showCarousel = computed(() => {
  if (typeof window === 'undefined') {
    // SSR 环境默认显示轮播
    return true
  }
  const width = window.innerWidth
  return (
    (props.modelValue?.data?.length > 3 && width >= 1024) ||
    (props.modelValue?.data?.length > 2 && width >= 768 && width < 1024) ||
    width < 768
  );
})

const isShow = ref(true)

// Swiper 模块
const modules = [Navigation, Pagination, Autoplay]

// Swiper 断点配置
const breakpoints = {
  768: {
    slidesPerView: 3,
    slidesPerGroup: 1,
    spaceBetween: 16,
    shortSwipes: false,
  },
  1024: {
    slidesPerView: 4,
    slidesPerGroup: 1,
    spaceBetween: 16,
  },
}
const currentIndex = ref(0)
const isRerender = ref(false)
const swiperInstance = ref<any>()

// Swiper 事件处理 - 新版本写法
const onSwiperSlideChange = (swiper: any) => {
  currentIndex.value = swiper.realIndex ?? 0;
}

// 简化的点击处理函数
const handleSlideClick = (index: number) => {
  profileData.value = props.modelValue?.data?.[index]
  showProfile.value = true
}

const onSwiperReady = (swiper: any) => {
  swiperInstance.value = swiper
  if (!isRerender.value) {
    nextTick(() => {
      setTimeout(() => {
        reRender()
      }, 100);
    })
  }
}
const reRender = (() => {
  isShow.value = false;
  nextTick(() => {
    isShow.value = true;
    nextTick(() => {
      if (swiperInstance.value) {
        swiperInstance.value.update();
        isRerender.value = true;
      }
    });
  });
})

const pageCount = computed(() => {
  return props.modelValue?.data?.length;
})

// 分页控制函数 - 新版本写法
const updatePage = ((idx: number) => {
  if (swiperInstance.value) {
    swiperInstance.value.slideToLoop(idx, 600);
  }
})

const slidePrev = () => {
  if (swiperInstance.value) {
    swiperInstance.value.slidePrev(600);
  }
}

const slideNext = () => {
  if (swiperInstance.value) {
    swiperInstance.value.slideNext(600);
  }
}

const handleInit = () => {
  if (props.modelValue && props.modelValue?.data) return // 有数据不用初始化
  const data = {
    id: props.modelValue?.id || randomString(),
    type: 'CardCarousel',
    width: '',
    data: [
      {
        id: randomString(),
        logo: 'https://ywies-tx.cedim.cn/images/logo/logo-ycyw.png',
        title: '耀华国际教育',
        subTitle: '耀华国际教育学校浙江桐乡',
        name: '耀华国际',
        label: '123',
        imgSrc: 'https://osswebsite.ycyw.com/media-library/ywies-bj/images/home/ywies-tx.jpg',
        alt: '',
        buttonList: {
          id: randomString(),
          type: 'BtnList',
          readOnly: true,
          width: '',
          bgColor: '',
          data: [
            {
              id: randomString(),
              type: 'white',
              text: '了解更多',
              url: 'https://www.baidu.com',
              isExternal: false
            },
            {
              id: randomString(),
              type: 'light',
              text: '了解更多',
              url: 'https://www.baidu.com',
              isExternal: false
            }
          ]
        },
        paragraphs: [{
          id: randomString(),
          title: '123',
          content: '123'
        }]
      }
    ]
  }
  emit('update:modelValue', data)
} 

const isHover = ref<boolean>(false);
const showSetting = ref<boolean>(false);

const handleDelete = () => {
  emit('handleDelete', props.modelValue?.id)
}

const handleCopy = () => {
  emit('handleCopy', props.modelValue)
}

const handlePaste = (type: string) => {
  emit('handlePaste', type)
}

const showProfile = ref<boolean>(false)
const profileData = ref<any>({})
const handleClick = (item: any) => {
  profileData.value = item
  showProfile.value = true
}

onMounted(() => {
  reRender()
})

handleInit()
</script>

<style lang="scss" scoped>
.card-carousel {
  position: relative;
}

/* Migrated minimal global utilities from global.scss for self-contained component */
.card-carousel {
  /* grid gutters used by many layouts */
  .row {
    --bs-gutter-x: 16px;
    --bs-gutter-y: 0;
    display: flex;
    flex-wrap: wrap;
    margin-top: calc(var(--bs-gutter-y)*-1);
    margin-right: calc(var(--bs-gutter-x)*-0.5);
    margin-left: calc(var(--bs-gutter-x)*-0.5)
  }

  .row>* {
    flex-shrink: 0;
    width: 100%;
    max-width: 100%;
    padding-right: calc(var(--bs-gutter-x)*0.5);
    padding-left: calc(var(--bs-gutter-x)*0.5);
    margin-top: var(--bs-gutter-y)
  }

  .col {
    flex: 1 0 0%
  }

  .row-cols-1>* {
    flex: 0 0 auto;
    width: 100%
  }

  .row-cols-md-3>* {
    flex: 0 0 auto;
    width: 33.3333333333%
  }

  .row-cols-lg-4>* {
    flex: 0 0 auto;
    width: 25%
  }

  /* center justification utility */
  .justify-content-center {
    justify-content: center;
  }

  /* simple spacing utilities used by this component */
  & .mt-10 { margin-top: 40px; }
  @media(min-width: 768px) {
    & .mt-md-12 { margin-top: 48px; }
  }

  /* image helpers */
  .img-fit {
    width: 100%;
  }

  .img-fit .img,.img-fit img {
    width: 100%;
    height: auto;
  }

  .img-wrapper {
    position: relative;
    height: 0;
    width: 100%
  }
}

@media(max-width: 767.98px) {
  .card-carousel__wrapper {
    padding-left:0;
    padding-right: 0;
  }
}

.card-carousel__wrapper .swiper .swiper-slide {
  pointer-events: auto; // 允许卡片交互
  flex-shrink: 0;
}

@media(max-width: 767.98px) {
  .card-carousel__wrapper .swiper .swiper-slide {
    padding-left: 32px;
    padding-right: 32px;
  }
}

.card-carousel__wrapper .swiper .swiper-slide .slide-content {
  pointer-events: auto;
}

.card-carousel .row {
  --bs-gutter-x: 16px;
  --bs-gutter-y: 80px;
}

@media(max-width: 767.98px) {
  .card-carousel .row {
    --bs-gutter-y:40px;
  }
}

.card-carousel__title {
  color: #0032a0;
  margin-bottom: 24px;
}

@media(max-width: 767.98px) {
  .card-carousel__title {
    margin-bottom: 12px;
  }
}

.card-profile .profile__head {
  position: relative;
}

.card-profile .profile__head .profile__img {
  overflow: hidden;
}

.card-profile .profile__head .profile__img.--show-profile {
  cursor: pointer;
}

@media(min-width: 768px) {
  .card-profile .profile__head .profile__img.--show-profile:hover .profile__img__mask {
    background-color:rgba(0,0,0,.4);
    opacity: 1;
  }
}

.card-profile .profile__head .profile__img__mask {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: transparent;
  transition: background-color .25s ease-out;
  opacity: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.card-profile .profile__head .profile__img__mask__btn {
  font-size: 16px;
  font-weight: 500;
  line-height: 1.5;
  letter-spacing: .01em;
  text-align: center;
  color: #f7f7fa;
  padding: 6px 10px;
  min-width: 140px;
  border: 1px solid #f7f7fa;
  border-radius: 2px;
}

@media(max-width: 1023.98px) {
  .card-profile .profile__head .profile__img__mask__btn {
    line-height: 1.25;
    letter-spacing: .04em;
  }
}

@media(max-width: 767.98px) {
  .card-profile .profile__head .profile__img__mask__btn {
    font-size:14px;
    line-height: 1.285;
    letter-spacing: .02em;
    min-width: 100px;
  }
}

.card-profile .profile__body {
  text-decoration: none;
  padding-bottom: 12px;
}

@media(max-width: 767.98px) {
  .card-profile .profile__body.is-single-column {
    padding-left: 12px;
    padding-right: 12px;
  }
}

.card-profile .profile__body.--show-profile {
  cursor: pointer;
}

.card-profile .profile__body .profile__title {
  color: #0048e8;
  color: var(--primary-color,#0048e8);
}

.card-profile .profile__body .profile__name {
  color: #0032a0;
  color: var(--text-color--secondary,#0032a0);
}

.row {
  flex-wrap: nowrap !important;
  overflow: hidden !important;
}

.card-content {
  transition: transform .4s ease-in-out;
}

:deep(.swiper) {
  overflow: hidden;
}
:deep(.swiper-wrapper) {
  display: flex;
  align-items: flex-start;
}
</style>